package com.adprof.demo.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.adprof.demo.android.R;
import com.adprof.demo.utils.ConstantsDemo;

public class MainActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    
    private MainFragment mMainFragment;
    private FrameLayout fragmentContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentContainer = findViewById(R.id.fragment_container);
        
        // 请求位置权限
//        requestLocationPermission();
        
        createMainFragment();
    }
    
    /**
     * 请求位置权限
     */
    private void requestLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否已有权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                
                // 显示权限说明（可选）
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                    Toast.makeText(this, "需要位置权限以便为您提供更好的广告服务", Toast.LENGTH_SHORT).show();
                }
                
                // 请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                        LOCATION_PERMISSION_REQUEST_CODE);
            } else {
                Log.d(ConstantsDemo.LOG_TAG, "位置权限已授予");
            }
        }
    }
    
    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0) {
                boolean allGranted = true;
                for (int result : grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allGranted = false;
                        break;
                    }
                }
                
                if (allGranted) {
                    Log.d(ConstantsDemo.LOG_TAG, "位置权限授予成功");
                    Toast.makeText(this, "位置权限已授予", Toast.LENGTH_SHORT).show();
                } else {
                    Log.d(ConstantsDemo.LOG_TAG, "位置权限被拒绝");
                    Toast.makeText(this, "位置权限被拒绝，部分功能可能无法使用", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void createMainFragment() {
        if (mMainFragment == null) {
            Intent intent = getIntent();
            String[] logs = intent.getStringArrayExtra("logs");
            mMainFragment = MainFragment.newInstance(logs);
            getSupportFragmentManager().beginTransaction().replace(fragmentContainer.getId(), mMainFragment).commit();
        }
    }

    @Override
    public void onStateNotSaved() {
        super.onStateNotSaved();
        mMainFragment.onResume();
    }

    @Override
    public void onBackPressed() {
        Log.d(ConstantsDemo.LOG_TAG, "onBackPressed() called " + getSupportFragmentManager().getBackStackEntryCount());
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
        }
    }
}